﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using PaperRenderingInterfaces;
using DeepZoomPivotConstructor.PivotLib;
using HtmlAgilityPack;
using PaperPluginUtilities;

namespace CMSPages
{
    /// <summary>
    /// Scan the master CMS page for event page renderings - and runt them. :-)
    /// </summary>
    [Export(typeof(IPaperRender))]
    [PaperRender("CMSMasterEventDisplayPage")]
    public class ScanMasterCMSEventDisplayPage : IPaperRender
    {
#pragma warning disable 0649
        [Import]
        IWebAccess WebGetter;
#pragma warning restore 0649

#pragma warning disable 0649
        [Import]
        IPaperRenderEngine PaperEngine;
#pragma warning restore 0649

        /// <summary>
        /// Drives the render to look for links to other pages with event images on them.
        /// </summary>
        /// <param name="renderAddress"></param>
        /// <returns></returns>
        public IEnumerable<PivotImage> Render(string renderAddress)
        {
            ///
            /// Fetch the web data
            ///

            Uri masterUri = new Uri(renderAddress);
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(WebGetter.GetUriAsString(masterUri));

            ///
            /// Now, scan for the links
            /// 

            var links = new EnumerableWrapper<HtmlNode>(doc.DocumentNode.SelectNodes("//a"));
            var imagePages = from l in links
                             let href = l.Attributes["href"]
                             where href != null
                             let subUri = new Uri(masterUri, href.Value)
                             where GoodEventPage(subUri)
                             group subUri by subUri.OriginalString;

            return imagePages.SelectMany(l => PaperEngine.Render("CMSEventDisplayPage", l.FirstOrDefault().OriginalString));

        }

        /// <summary>
        /// Determine if this url is a good one for a web page that shows off some images.
        /// </summary>
        /// <param name="subUri"></param>
        /// <returns></returns>
        private bool GoodEventPage(Uri subUri)
        {
            if (!subUri.OriginalString.EndsWith(".htm") && !subUri.OriginalString.EndsWith(".html"))
            {
                return false;
            }

            /// Get rid of the master page! :-)
            if (subUri.OriginalString.Contains("EventDisplays/index.html"))
                return false;

            return subUri.OriginalString.Contains("Media/Images/EventDisplays");
        }
    }
}
